$(function () {
    $("#jqGrid").Grid({
        url: '../sale/book/list',
        colModel: [
			{label: 'id', name: 'id', align:'center', index: 'id', key: true, hidden: true},
			{label: '合同编号', name: 'bookNo', align:'center', index: 'bookNo', width: 80},
			{label: '客户姓名', name: 'customerName', align:'center', index: 'customer_id', width: 80},
			{label: '客户手机', name: 'saleCustomerInfo.phone', align:'center', index: 'customer_id', width: 80},
			{label: '销售姓名', name: 'personName', align:'center', index: 'person_id', width: 80},
			{label: '销售手机', name: 'personPhone', align:'center', index: 'person_id', width: 80},
			{label: '付款方式', name: 'payment', align:'center', index: 'payment', width: 80, formatter: function (value) {
                return value === 1 ?
                        '<span class="label label-danger">全款</span>' :
                        '<span class="label label-success">分期</span>';
                }
			},
			{label: '合同金额', name: 'sumAmount', align:'center', index: 'deposit', width: 80},
			{label: '定金', name: 'deposit', align:'center', index: 'sum_amount', width: 80},
			{label: '状态', name: 'state', align:'center', index: 'state', width: 80, formatter: function (value) {
					if(value === 1){
						return "待审批";
					}else if(value === 2){
						return "待收定金";
					}else if(value === 3){
						return "待分车";
					}else if(value === 4){
						return "待付款";
					}else if(value === 5){
						return "完成";
					}else if(value === 6){
						return "待修改";
					}else if(value === 9){
						return "作废";
					}else{
						return '<span class="label label-danger">错误状态</span>';
					}
				}
			},
			{label: '订单日期', name: 'createTime', align:'center', index: 'create_time', width: 80}]
    });
});

var vm = new Vue({
	el: '#rrapp',
	data: {
        showList: true,
        title: null,
        editBook:false,
        cancelOper:false,
        approveOper:false,
        allotOper:false,
        receiptOper:false,
        depositOper:false,
        detailOper:false,
		detailReadonly:false,
		financeName:"",
		saleBook: {},
		boutiquesId:"boutiqueTableId",
		carNum:1,
		ruleValidate: {
//			name: [
//				{required: true, message: '名称不能为空', trigger: 'blur'}
//			]
		},
		q: {
		    name: '',
			phone:'',
			personName: '',
			personPhone: '',
			payment: '',
			state: ''
		}
	},
	methods: {
		changeResidue:function(){
			var payType=1;
			var downPaymentSum=0;
			if(vm.saleBook.saleCarList&&vm.saleBook.saleCarList.length>0){
				for (var i = 0; i < vm.saleBook.saleCarList.length; i++) {
					if(2==vm.saleBook.saleCarList[i].payment){
						downPaymentSum=vm.saleBook.saleCarList[i].downPaymentSum;
						payType=2;
						break;
					}
				}
			}
			if(1==payType){
				vm.saleBook.residue=vm.saleBook.sumAmount-vm.saleBook.deposit;
			}else{
				vm.saleBook.residue=downPaymentSum-vm.saleBook.deposit;
			}
		},
		selectStoreCar:function(cindex){
			if (vm.detailReadonly){
				return;
			}
			openWindow({
	        	type: 2,
	            title: "选择车辆",
	            area: ['80%', '60%'],
	            content: ['../stock/stockreal.html?state=1&productId='+vm.saleBook.saleCarList[cindex].productCarId],
	            btn: ['确定', '取消'],
	            btn1: function (index,layero) {
	            	var selectRowData = window[layero.find('iframe')[0]['name']].getSelectedRowData('#jqGrid');
	            	vm.saleBook.saleCarList[cindex].vin=selectRowData.vin;
	                layer.close(index);
	            }
	        });
		},
		selectFinance:function(fIndex){
			openWindow({
				type: 2,
				title: "选择金融公司",
				area: ['80%', '60%'],
				content: ['../sale/basefinancecompany.html'],
				btn: ['确定', '取消'],
				btn1: function (index,layero) {
					var selectRowData = window[layero.find('iframe')[0]['name']].getSelectedRowData('#jqGrid');
					vm.saleBook.saleCarList[fIndex].financecompanyId=selectRowData.id;
					vm.saleBook.saleCarList[fIndex].financecompanyName=selectRowData.name
//					vm.saleBook.saleCarList[fIndex].financePoundage=selectRowData.poundage;
					vm.saleBook.saleCarList[fIndex].financeProfit=selectRowData.profit;
					layer.close(index);
				}
			});
		},
		selectInsurance:function(fIndex){
			openWindow({
				type: 2,
				title: "选择保险公司",
				area: ['80%', '60%'],
				content: ['../sale/baseinsurancecompany.html'],
				btn: ['确定', '取消'],
				btn1: function (index,layero) {
					var selectRowData = window[layero.find('iframe')[0]['name']].getSelectedRowData('#jqGrid');
					vm.saleBook.saleCarList[fIndex].insurancecompanyId=selectRowData.id;
					vm.saleBook.saleCarList[fIndex].insurancecompanyName=selectRowData.name;
					vm.saleBook.saleCarList[fIndex].insuranceType=selectRowData.type;
					vm.saleBook.saleCarList[fIndex].insurancePoundage=selectRowData.poundage;
					vm.saleBook.saleCarList[fIndex].insuranceProfit=selectRowData.profit;
					layer.close(index);
				}
			});
		},
		allotCar:function(){
			var id = getSelectedRow("#jqGrid");
			if (id == null) {
				return;
			}
			vm.showList = false;
			vm.cancelOper=false;
			vm.approveOper=false;
			vm.receiptOper=false;
			vm.detailOper=false;
			vm.editBook=false;
			vm.allotOper=true;
            vm.title = "分配销售车辆";
            vm.getInfo(id,9);
		},
		cancelBook:function(){
			var id = getSelectedRow("#jqGrid");
			if (id == null) {
				return;
			}
			vm.showList = false;
			vm.cancelOper=true;
			vm.approveOper=false;
			vm.allotOper=false;
			vm.receiptOper=false;
			vm.detailOper=false;
			vm.editBook=false;
            vm.title = "作废销售合同";
            vm.getInfo(id,1);
		},
		depositBook:function(){
			var id = getSelectedRow("#jqGrid");
			if (id == null) {
				return;
			}
			vm.showList = false;
			vm.cancelOper=false;
			vm.allotOper=false;
			vm.receiptOper=true;
			vm.detailOper=false;
			vm.approveOper=false;
			vm.editBook=false;
			vm.depositOper=true;
            vm.title = "销售合同定金";
            vm.getInfo(id,1);
		},
		approveBook:function(){
			var id = getSelectedRow("#jqGrid");
			if (id == null) {
				return;
			}
			vm.showList = false;
			vm.cancelOper=false;
			vm.allotOper=false;
			vm.receiptOper=false;
			vm.detailOper=false;
			vm.approveOper=true;
			vm.editBook=false;
			vm.title = "审核销售合同";
			vm.getInfo(id,1);
		},
		receiptBook:function(){
			var id = getSelectedRow("#jqGrid");
			if (id == null) {
				return;
			}
			vm.showList = false;
			vm.cancelOper=false;
			vm.approveOper=false;
			vm.allotOper=false;
			vm.detailOper=false;
			vm.receiptOper=true;
			vm.editBook=false;
			vm.depositOper=false;
            vm.title = "销售合同收款";
            vm.getInfo(id,1);
		},
		detailBook:function(){
			var id = getSelectedRow("#jqGrid");
			if (id == null) {
				return;
			}
			vm.cancelOper=false;
			vm.approveOper=false;
			vm.allotOper=false;
			vm.receiptOper=false;
			vm.detailOper=false;
			vm.detailReadonly=true;
			vm.showList = false;
			vm.editBook=true;
            vm.title = "销售合同详情";
            vm.getInfo(id,4);
		},
		printDetail:function(){
			var id = getSelectedRow("#jqGrid");
			if (id == null) {
				return;
			}
			
			window.location.href="../sale/book/printDetail?id="+id;
//			var url = "../sale/book/printDetail";
//			// 构造隐藏的form表单
//			var $form = $("<form id='downloadPrintDetail' class='hidden' method='post'></form>");
//			$form.attr("url",url);
//			$(body).append($form);
//			// 添加提交参数
//			var $input1 = $("<input name='id' type='text'></input>");
//			$input1.attr("value",id);
//			$("#download").append($input1);
//			// 提交表单
//			$form.submit();
		},
		selectCarModel:function(pIndex){
			if (vm.detailReadonly){
				return;
			}
			openWindow({
            	type: 2,
                title: "选择车型",
                area: ['80%', '60%'],
                content: ['../product/productcar.html'],
                btn: ['确定', '取消'],
                btn1: function (index,layero) {
                	var selectRowData = window[layero.find('iframe')[0]['name']].getSelectedRowData('#jqGrid');
                	vm.saleBook.saleCarList[pIndex].productCarId=selectRowData.id;
            		vm.saleBook.saleCarList[pIndex].productCarName=selectRowData.carSerie+" "+selectRowData.carModel+" "+selectRowData.design+" "+selectRowData.config+" "+selectRowData.colour;
                    layer.close(index);
                }
            });
		},
		deleteMedal:function(index){
			vm.saleBook.saleCarList[index].showCar=false;
		},
		addStoreCar:function(){
			var payTypeAging=false;
			var carNum=0;
			for (var i = 0; i < vm.saleBook.saleCarList.length; i++) {
				if(vm.saleBook.saleCarList[i].showCar){
					carNum=carNum+1;
					if(2==vm.saleBook.saleCarList[i].payment){
						payTypeAging=true;
						break;
					}
				}
			}
			if(carNum>0&&payTypeAging){
				alert("分期的方式，一个合同只能有一辆车");
			}else{
				var bqId=vm.boutiquesId+(vm.carNum-1);
				vm.saleBook.saleCarList.push({productCarId:null,productCarName:"",payment:1,overDate:null,plateCost:null,showCar:true,saleBoutiqueList:[],
					acquireCost:null,insuranceCost:null,sumCost:null,downPayment:null,nper:null,monthPayment:null,
					financecompanyId:null,financecompanyName:"",financePoundage:0,financeProfit:0,
					insurancecompanyId:null,insurancecompanyName:"",insuranceType:null,insurancePoundage:0,insuranceProfit:0,trafficCost:0,
					boutiqueTable:bqId});
				vm.carNum+=1;
			}
		},
		addSaleBoutique:function(index){
			vm.saleBook.saleCarList[index].saleBoutiqueList.push({boutiqueName:"",boutiqueId:null,price:0,num:1,sumCost:0,showbp:true});
		},
		deleteBoutique:function(index,bIndex){
			vm.saleBook.saleCarList[index].saleBoutiqueList[bIndex].showbp=false;
		},
		selectBoutiqueModel:function(cIndex,bIndex){
			openWindow({
            	type: 2,
                title: "选择精品",
                area: ['80%', '60%'],
                content: ['../product/productboutique.html?state=1'],
                btn: ['确定', '取消'],
                btn1: function (index,layero) {
                	var selectRowData = window[layero.find('iframe')[0]['name']].getSelectedRowsData('#jqGrid');
                	if(selectRowData){
                		if(selectRowData.length){
                			for (var i = 0; i < selectRowData.length; i++) {
								if(i==0){
									vm.saleBook.saleCarList[cIndex].saleBoutiqueList[bIndex].boutiqueId=selectRowData[i].id;
		                        	vm.saleBook.saleCarList[cIndex].saleBoutiqueList[bIndex].boutiqueName=selectRowData[i].name;
		                        	vm.saleBook.saleCarList[cIndex].saleBoutiqueList[bIndex].price=selectRowData[i].price;
								}else{
									vm.addSaleBoutique(cIndex);
									vm.saleBook.saleCarList[cIndex].saleBoutiqueList[bIndex+i].boutiqueId=selectRowData[i].id;
		                        	vm.saleBook.saleCarList[cIndex].saleBoutiqueList[bIndex+i].boutiqueName=selectRowData[i].name;
		                        	vm.saleBook.saleCarList[cIndex].saleBoutiqueList[bIndex+i].price=selectRowData[i].price;
								}
							}
                		}else{
                			vm.saleBook.saleCarList[cIndex].saleBoutiqueList[bIndex].boutiqueId=selectRowData.id;
                        	vm.saleBook.saleCarList[cIndex].saleBoutiqueList[bIndex].boutiqueName=selectRowData.name;
                        	vm.saleBook.saleCarList[cIndex].saleBoutiqueList[bIndex].price=selectRowData.price;
                		}
                	}
                    layer.close(index);
                }
            });
		},
		changePayment:function(index){
			var payType=vm.saleBook.saleCarList[index].payment;
			var carNum=0;
			for (var i = 0; i < vm.saleBook.saleCarList.length; i++) {
				if(vm.saleBook.saleCarList[i].showCar){
					carNum=carNum+1;
				}
			}
			if(2==payType&&carNum>1){
				alert("分期的方式，一个合同只能有一辆车");
				vm.saleBook.saleCarList[index].payment=1;
			}
			vm.changeResidue();
		},
		selectCustomer:function(){
			if (vm.detailReadonly){
				return;
			}
			openWindow({
            	type: 2,
                title: "选择车型",
                area: ['80%', '60%'],
                content: ['../sale/salecustomer.html'],
                btn: ['确定', '取消'],
                btn1: function (index,layero) {
                	var selectRowData = window[layero.find('iframe')[0]['name']].getSelectedRowData('#jqGrid');
                	vm.saleBook.customerId=selectRowData.id;
                	vm.saleBook.customerName=selectRowData.name+"  "+selectRowData.phone;
                	vm.saleBook.tel=selectRowData.phone;
                    layer.close(index);
                }
            });
		},
		query: function () {
			vm.reload();
		},
		add: function () {
			vm.carNum=1;
			vm.showList = false;
			vm.cancelOper=false;
			vm.approveOper=false;
			vm.receiptOper=false;
			vm.detailOper=false;
			vm.allotOper=false;
			vm.editBook=true;
			vm.title = "新增";
			vm.saleBook = {payment:1,customerId:null,customerName:"",saleCarList:[]};
			vm.addStoreCar();
		},
		update: function (event) {
            var id = getSelectedRow("#jqGrid");
			if (id == null) {
				return;
			}
			vm.showList = false;
			vm.cancelOper=false;
			vm.approveOper=false;
			vm.receiptOper=false;
			vm.detailOper=false;
			vm.allotOper=false;
			vm.editBook=true;
            vm.title = "修改";
            vm.getInfo(id);
		},
		saveOrUpdate: function (event) {
			var saleCarList=[];
			for (var i = 0; i < vm.saleBook.saleCarList.length; i++) {
				if(vm.saleBook.saleCarList[i].showCar){
					var saleBoutiqueList=[];
					for (var j = 0; j < vm.saleBook.saleCarList[i].saleBoutiqueList.length; j++) {
						if(vm.saleBook.saleCarList[i].saleBoutiqueList[j].showbp){
							saleBoutiqueList.push(vm.saleBook.saleCarList[i].saleBoutiqueList[j]);
						}
					}
					vm.saleBook.saleCarList[i].saleBoutiqueList=saleBoutiqueList;
					saleCarList.push(vm.saleBook.saleCarList[i]);
					var overDate=vm.saleBook.saleCarList[i].overDate;
					vm.saleBook.saleCarList[i].overDate=formatDateToDate(overDate);
					if(2==vm.saleBook.saleCarList[i].payment){
						vm.saleBook.payment=2;
					}
				}
			}
			vm.saleBook.saleCarList=saleCarList;
			
//            var url = vm.saleBook.id == null ? "../sale/book/save" : "../sale/book/update";
            var url = "../sale/book/save";
            Ajax.request({
			    url: url,
                params: JSON.stringify(vm.saleBook),
                type: "POST",
			    contentType: "application/json",
                successCallback: function (r) {
                    alert('操作成功', function (index) {
                        vm.reload();
                    });
                }
			});
		},
		del: function (event) {
            var ids = getSelectedRows("#jqGrid");
			if (ids == null){
				return;
			}

			confirm('确定要删除选中的记录？', function () {
                Ajax.request({
				    url: "../sale/book/delete",
                    params: JSON.stringify(ids),
                    type: "POST",
				    contentType: "application/json",
                    successCallback: function () {
                        alert('操作成功', function (index) {
                            vm.reload();
                        });
					}
				});
			});
		},
		getInfo: function(id,state){
			var param="";
			if(state){
				param="?state="+state;
			}
            Ajax.request({
                url: "../sale/book/info/"+id+param,
                async: true,
                successCallback: function (r) {
                    vm.saleBook = r.saleBook;
                    if (r.saleBook.payment==2){
						vm.financeName=r.saleBook.financeName;
						vm.saleBook.saleCarList[0].payment=2;
					}
                }
            });
		},
		cancel: function(){
            Ajax.request({
                url: "../sale/book/cancel?id="+vm.saleBook.id,
                contentType: "application/json",
                successCallback: function () {
                    alert('操作成功', function (index) {
                        vm.reload();
                    });
				}
            });
		},
		allot: function(){
			if(vm.saleBook.saleCarList.length>0){
				for (var i = 0; i < vm.saleBook.saleCarList.length; i++) {
					vm.saleBook.saleCarList[i].overDate="";
				}
			}
			Ajax.request({
				url: "../sale/car/allot",
				async: true,
				params: JSON.stringify(vm.saleBook.saleCarList),
				type: "POST",
				contentType: "application/json",
				successCallback: function () {
					alert('操作成功', function (index) {
						vm.reload();
					});
				}
			});
		},
		audityes: function(){
			Ajax.request({
				url: "../sale/book/audityes?id="+vm.saleBook.id,
				async: true,
				contentType: "application/json",
				successCallback: function () {
					alert('操作成功', function (index) {
						vm.reload();
					});
				}
			});
		},
		auditno: function(){
			Ajax.request({
				url: "../sale/book/auditno?id="+vm.saleBook.id,
				async: true,
				contentType: "application/json",
				successCallback: function () {
					alert('操作成功', function (index) {
						vm.reload();
					});
				}
			});
		},
		receipt: function(){
			if(vm.depositOper){
				Ajax.request({
					url: "../sale/book/deposit?id="+vm.saleBook.id,
					async: true,
					contentType: "application/json",
					successCallback: function () {
						alert('操作成功', function (index) {
							vm.reload();
						});
					}
				});
			}else{
				Ajax.request({
					url: "../sale/book/receipt?id="+vm.saleBook.id,
					async: true,
					contentType: "application/json",
					successCallback: function () {
						alert('操作成功', function (index) {
							vm.reload();
						});
					}
				});
			}
		},
		reload: function (event) {
			vm.showList = true;
			vm.detailReadonly=false;
			vm.financeName=""
            var page = $("#jqGrid").jqGrid('getGridParam', 'page');
			$("#jqGrid").jqGrid('setGridParam', {
                postData: {
                	'name': vm.q.name,
					'phone':vm.q.phone,
					'personName':vm.q.personName,
					'personPhone':vm.q.personPhone,
					'payment':vm.q.payment,
					'state':vm.q.state
				},
                page: 1
            }).trigger("reloadGrid");
            vm.handleReset('formValidate');
		},
        reloadSearch: function() {
            vm.q = {
				name: '',
				phone:'',
				personName: '',
				personPhone: '',
				payment: '',
				state: ''
            };
            vm.reload();
        },
        handleSubmit: function (name) {
            handleSubmitValidate(this, name, function () {
                vm.saveOrUpdate()
            });
        },
        handleReset: function (name) {
            handleResetForm(this, name);
        }
	}
});